package com.justgame.project.service.art.service;

import com.alibaba.fastjson.JSONObject;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.exception.Exc;
import com.justgame.project.cloud.common.util.IdUtils;
import com.justgame.project.cloud.common.util.ObjUtil;
import com.justgame.project.cloud.common.util.ShiroUtils;
import com.justgame.project.cloud.common.entity.PageRequest;
import com.justgame.project.service.api.dto.ArtPageInfoDTO;
import com.justgame.project.service.api.entity.ArtPageGameMap;
import com.justgame.project.service.api.entity.ArtPageInfo;
import com.justgame.project.service.api.vo.ArtPageInfoVO;
import com.justgame.project.service.art.mapper.ArtPageGameMapMapper;
import com.justgame.project.service.art.mapper.ArtPageInfoMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Data
@Slf4j
@Service
@Transactional
public class ArtPageInfoService {
    @Resource
    private ArtPageInfoMapper artPageInfoMapper;
    @Resource
    private ArtPageGameMapMapper artPageGameMapMapper;

    @Cacheable(cacheNames = {"ArtPage"},key = "'homeIndexPage:'+ #dto.pageCategory")
    public List<ArtPageInfoVO> homeIndexPage(ArtPageInfoDTO dto) {
        List<ArtPageInfoVO> vos = artPageInfoMapper.selectIndexList(dto);
        if (vos != null && vos.size() > 0) {
            Do(vos);
        }
        return vos;
    }

    /**
     * 上传文章
     *
     * @param dto 上传的数据
     * @return Boolean
     */
    @CacheEvict(cacheNames = {"ArtPage"})
    public Boolean save(ArtPageInfoDTO dto) {
        String userId = ShiroUtils.getUserId();
        if (StringUtils.isBlank(userId)) {
            throw new Exc("请先登录再试！");
        }
        if (StringUtils.isBlank(dto.getPageContent())) {
            throw new Exc("请先检查所提交的内容！");
        }
        ObjUtil.inject(dto, true);
        List<String> gameIds = dto.getGameIds();
        if (gameIds != null && gameIds.size() > 0) {
            gameIds.forEach(gameId -> {
                ArtPageGameMap pgMap = new ArtPageGameMap();
                pgMap.setId(IdUtils.create());
                pgMap.setPageId(dto.getId());
                pgMap.setGameId(gameId);
                pgMap.setCreateDate(new Date());
                pgMap.setCreateUser(userId);
                artPageGameMapMapper.saveMap(pgMap);
            });
        }
        return artPageInfoMapper.insertOne(dto) > 0;
    }

    /**
     * RAW文件内容解析
     */
    public void Do(List<ArtPageInfoVO> artPageInfos) {
        artPageInfos.forEach(vo -> {
            try {
                if (StringUtils.isBlank(vo.getPageContent())) {
                    return;
                }
                Map<String, Object> obj = JSONObject.parseObject(vo.getPageContent());
                List<Map> infoList = (List<Map>) obj.get("blocks");
                StringBuilder ArticleStr = new StringBuilder();
                for (Map item : infoList) {
                    if (item.get("text") != null && StringUtils.isNotBlank(String.valueOf(item.get("text")))) {
                        ArticleStr.append(item.get("text"));
                    }
                }
                String contentStr = ObjUtil.removeMoreBlank(ArticleStr.toString());
                Integer fontSize = contentStr.length();
                vo.setSimpleText(contentStr);
                vo.setFontSize(fontSize);
            } catch (Exception e) {
                log.error(e.getLocalizedMessage());
            }
        });
    }

    public PageRequest<ArtPageInfoVO> queryByPage(PageRequest<ArtPageInfoVO> pageRequest, ArtPageInfoDTO dto) {
        pageRequest.startPage();
        List<ArtPageInfoVO> pages = artPageInfoMapper.select(dto);
        if (pages != null && pages.size() > 0) {
            Do(pages);
        }
        return pageRequest.BuildPageInfo(pages);
    }

    /**
     * 逻辑删除
     *
     * @param id 主键id
     * @return Boolean
     */
    @CacheEvict(cacheNames = {"ArtPage"} ,key = "'id:'+#id")
    public boolean deleteById(String id) {
        return artPageInfoMapper.deleteById(id);
    }

    /**
     * 查看文章详情
     *
     * @param id 主键id
     * @return ArtPageInfoVO.class
     */
    @Cacheable(cacheNames = {"ArtPage"} ,key = "'id:'+#id")
    public ArtPageInfoVO getPageDetail(String id) {
        if (StringUtils.isNotBlank(id)) {
            ArtPageInfo art = new ArtPageInfo();
            art.setId(id);
            List<ArtPageInfoVO> list = artPageInfoMapper.select(art);
            if (list.size() > 0) {
                ArtPageInfoVO detail = list.get(0);
                detail.setRelevantGames(artPageGameMapMapper.getGames(id));
                return list.get(0);
            }
        } else {
            throw new Exc(Const.RES_BAD_PARAMS_CHINESE, Const.RES_BAD_PARAMS);
        }
        return null;
    }

}
